package com.hxc.pay.wx.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxc.pay.NativePayTemplate;
import com.hxc.pay.wx.config.WxPayProperties;
import com.hxc.pay.wx.dto.Amount;
import com.hxc.pay.wx.dto.NativePayDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

@Slf4j
public class WxNativePayTemplate implements NativePayTemplate {

    private WxPayProperties wxPayProperties;
    private CloseableHttpClient httpClient;


    public WxNativePayTemplate(WxPayProperties wxPayProperties, CloseableHttpClient httpClient) {
        this.wxPayProperties = wxPayProperties;
        this.httpClient = httpClient;
    }

    @Override
    public String createOrder(Integer total, String description, String outTradeNo) {
        String resStr = null;
        try {
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
            // 请求body参数

            Amount amount = Amount.builder().currency("CNY").total(1).build();

            NativePayDto nativePayDto = NativePayDto.builder().appid(wxPayProperties.getAppid())
                    .description(description)
                    .mchid(wxPayProperties.getMchId())
                    .notify_url(wxPayProperties.getNotifyUrl())
                    .out_trade_no(outTradeNo)
                    .amount(amount)
                    .build();


            String reqdata = JSON.toJSONString(nativePayDto);
            StringEntity entity = new StringEntity(reqdata,"utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");

            //完成签名并执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            resStr = "";
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) { //处理成功
                    System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                    // 使用 Fastjson 解析返回的 JSON 字符串
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
                    resStr = jsonObject.getString("code_url"); // 获取 code_url 字段
                    log.info("预支付URL：{}", resStr);
                    return resStr;
                } else if (statusCode == 204) { //处理成功，无返回Body
                    System.out.println("success");
                } else {
                    System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resStr;
    }
}
